from cStringIO import StringIO
import re
import os
from ftplib import FTP
path = os.path.abspath(os.path.dirname(__file__))

def update():
	rir_names = ['arin', 'ripe', 'afrinic', 'apnic', 'lacnic']
	for name in rir_names:
        	print name
        	ftp = FTP()
        	ftp.connect('ftp.'+name+'.net', 21)
        	ftp.login()
       		filename = ''
        	if name == 'ripe':
                	ftp.cwd('ripe/stats/')
                	filename = 'delegated-ripencc-latest'
        	else:
                	ftp.cwd('pub/stats/'+name+'/')
                	filename = 'delegated-'+name+'-latest'
        	file_handler = open(path+'/stats/'+filename, 'wb')
        	ftp.retrbinary('RETR '+filename, file_handler.write)
        	file_handler.close()
        	ftp.quit()
	
class RIR:
        def __init__(self, rir):
                self.rir = rir
                if rir == 'ripe':
                        self.rirfile = 'delegated-ripencc-latest'
                else:
                        self.rirfile = 'delegated-'+rir+'-latest'
        def get_all_asn_by_country(self, country):
                string = open(path + '/stats/'+self.rirfile).read()
                file = StringIO(string)
                asn = re.compile('\|'+country+'\|asn\|(\d+)\|(\d+)')
                result = []
                for line in file:
                        tmp = asn.findall(line)
                        if len(tmp) >= 1:
                                i = int(tmp[0][0])
                                j = int(tmp[0][1])
                                for n in range(j):
                                        if i > 65536:
                                                result.append(str(i/65536)+'.'+str(i%65536))
                                        else:
                                                result.append(str(i))
                                        i += 1
                return result
